// trap.c 
#include "printk.h"
#include "clock.h"
#include "syscall.h"

void trap_handler(unsigned long scause, unsigned long sepc, struct pt_regs *regs) {
    // 根据scause寄存器结构得知，通过检测scause寄存器最高位是否为1判断trap是否为interrupt
  	// 若trap是interrupt类型，通过检测剩余位是否为1<<5判断其是否是timer interrupt
    unsigned long high_b=1UL<<63; // 寄存器共64位，1<<63代表最高位为1
    if((scause & high_b) && (scause & 5 == 5)) {
        //printk("Supervisor Mode Timer Interrupt\n");
        clock_set_next_event(); // 设置下一次trap时间
        do_timer();
    }
    else if(scause == 0x08) {
        switch (regs->reg[17])
        {
        case SYS_WRITE:
            unsigned int fd_w = regs->reg[10];
            const char *buf_w = (const char *)regs->reg[11];
            int count_w = regs->reg[12];
            regs->reg[10] = sys_write(fd_w, buf_w, count_w);
            break;
        case SYS_GETPID:
            regs->reg[10] = sys_getpid();
            break;
        case SYS_READ:
            unsigned int fd_r = regs->reg[10];
            char *buf_r = (char *)regs->reg[11];
            uint64_t count_r = regs->reg[12];
            regs->reg[10] = sys_read(fd_r, buf_r, count_r);
            break;
        }
        regs->sepc += 4;
    }
}